<template>
  <div class="video-view-wrapper">
    <div class="video-header">
      <h4>视频列表</h4>
      <el-button type="primary" size="small" @click="showUploadDialog">
        <el-icon><Plus /></el-icon>上传视频
      </el-button>
    </div>
    
    <div v-if="videos.length === 0" class="video-placeholder">
      <el-empty description="暂无视频内容" :image-size="100" />
    </div>
    
    <div v-else class="video-list">
      <div v-for="video in videos" :key="video.id" class="video-card">
        <div class="video-info">
          <div class="video-thumbnail">
            <img v-if="video.coverUrl" :src="video.coverUrl" :alt="video.title" />
            <div v-else class="no-cover">
              <el-icon><VideoPlay /></el-icon>
            </div>
          </div>
          <div class="video-details">
            <h5 class="video-title">{{ video.title || '未命名视频' }}</h5>
            <div class="video-meta">
              <span v-if="video.playCount || video.playCount === 0" class="play-count">播放: {{ video.playCount || 0 }}</span>
              <span v-if="video.isFree === 1 || video.isFree === true" class="free-tag">免费</span>
              <span v-else-if="video.cost && video.cost > 0" class="cost-tag">¥{{ video.cost }}</span>
            </div>
            <p v-if="video.description" class="video-description">{{ video.description }}</p>
          </div>
        </div>
        <div class="video-actions">
          <el-button size="small" @click="editVideo(video)">
            <el-icon><Edit /></el-icon>
          </el-button>
          <el-button size="small" type="danger" @click="deleteVideo(video.id)">
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 视频上传对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传视频" width="600px">
      <el-form ref="videoFormRef" :model="videoForm" label-width="80px">
        <el-form-item label="视频文件" required>
          <el-upload
            class="upload-demo"
            drag
            action=""
            :auto-upload="false"
            :on-change="handleFileChange"
            :before-upload="beforeUpload"
            :limit="1"
            :file-list="fileList"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">
                支持 MP4、AVI 等常见视频格式
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="videoForm.title" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="视频描述">
          <el-input v-model="videoForm.description" type="textarea" placeholder="请输入视频描述" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="videoForm.sort" type="number" placeholder="请输入排序序号" />
        </el-form-item>
        <el-form-item label="是否免费">
          <el-switch v-model="videoForm.isFree" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item v-if="videoForm.isFree === 0" label="价格">
          <el-input v-model="videoForm.cost" type="number" placeholder="请输入价格" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="uploading" @click="submitVideo">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 视频编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑视频" width="600px">
      <el-form ref="editFormRef" :model="editForm" label-width="80px">
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入视频标题" />
        </el-form-item>
        <el-form-item label="视频描述">
          <el-input v-model="editForm.description" type="textarea" placeholder="请输入视频描述" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="editForm.sort" type="number" placeholder="请输入排序序号" />
        </el-form-item>
        <el-form-item label="是否免费">
          <el-switch v-model="editForm.isFree" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item v-if="editForm.isFree === 0" label="价格">
          <el-input v-model="editForm.cost" type="number" placeholder="请输入价格" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateVideo">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, defineProps, watch } from 'vue'
import { Plus, Edit, Delete, VideoPlay, UploadFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

// 定义props
const props = defineProps({
  chapter_id: {
    type: Number,
    required: true
  },
  course_id: {
    type: Number,
    required: true
  }
})

// 响应式数据
const videos = ref([])
const uploadDialogVisible = ref(false)
const editDialogVisible = ref(false)
const uploading = ref(false)
const videoFormRef = ref()
const editFormRef = ref()
const videoForm = ref({
  title: '',
  description: '',
  coverUrl: '',
  sort: 1,
  isFree: 1,
  cost: 0
})
const editForm = ref({
  id: null,
  title: '',
  description: '',
  sort: 1,
  isFree: 1,
  cost: 0
})
const fileList = ref([])  // 用于存储选择的文件

// 获取视频列表
const getVideoList = async () => {
  try {
    // 确保参数名与后端一致，使用驼峰命名法
    console.log('正在获取视频列表，章节ID:', props.chapter_id)
    const response = await request.get('/video/list', {
      params: { chapterId: props.chapter_id }
    })
    
    console.log('视频列表API响应:', response)
    
    if (response.code === 100) {
      // 确保视频数据格式化正确
      const formattedVideos = (response.data || []).map(video => ({
        ...video,
        // 确保必要字段有默认值
        playCount: video.playCount || 0,
        isFree: video.isFree !== undefined ? video.isFree : 1,
        cost: video.cost !== undefined ? video.cost : 0,
        sort: video.sort || 1
      }))
      videos.value = formattedVideos
      console.log('格式化后的视频列表:', formattedVideos)
    } else {
      ElMessage.error('获取视频列表失败: ' + (response.message || '未知错误'))
    }
  } catch (error) {
    console.error('获取视频列表错误:', error)
    ElMessage.error('网络错误: ' + (error.message || '请求失败'))
  }
}

// 显示上传对话框
const showUploadDialog = () => {
  videoForm.value = {
    title: '',
    description: '',
    coverUrl: '',
    sort: videos.value.length > 0 ? Math.max(...videos.value.map(v => v.sort || 0)) + 1 : 1,
    isFree: 1,
    cost: 0
  }
  fileList.value = []  // 清空文件列表
  uploadDialogVisible.value = true
}

// 编辑视频
const editVideo = (video) => {
  // 创建深拷贝以避免直接修改原始数据
  const videoCopy = JSON.parse(JSON.stringify(video))
  // 确保所有需要的字段都有默认值
  if (videoCopy.isFree === undefined) videoCopy.isFree = 1
  if (videoCopy.cost === undefined) videoCopy.cost = 0
  if (videoCopy.sort === undefined) videoCopy.sort = 1
  editForm.value = videoCopy
  editDialogVisible.value = true
}

// 处理文件变化 - 修复变量名冲突
const handleFileChange = (file, files) => {
  fileList.value = files.slice(-1) // 只保留最新的一个文件
}

// 自定义上传处理
const handleUpload = async (file) => {
  const formData = new FormData()
  formData.append('file', file)
  formData.append('courseId', props.course_id)
  formData.append('chapterId', props.chapter_id)
  formData.append('title', videoForm.value.title || file.name)
  formData.append('description', videoForm.value.description)
  formData.append('coverUrl', videoForm.value.coverUrl)
  formData.append('sort', videoForm.value.sort)
  formData.append('isFree', videoForm.value.isFree)
  formData.append('cost', videoForm.value.cost || 0)
  formData.append('userId', '1') // 这里应该从用户状态获取
  
  try {
    uploading.value = true
    const response = await request.post('/video/upload/file', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response
  } catch (error) {
    throw error
  } finally {
    uploading.value = false
  }
}

// 上传前验证
const beforeUpload = (file) => {
  const isVideo = file.type.includes('video/')
  const isLt500M = file.size / 1024 / 1024 < 500
  
  if (!isVideo) {
    ElMessage.error('请上传视频文件!')
    return false
  }
  if (!isLt500M) {
    ElMessage.error('视频大小不能超过 500MB!')
    return false
  }
  return true
}

// 上传成功处理
const onUploadSuccess = (response) => {
  if (response.code === 100) {
    ElMessage.success('上传成功')
    uploadDialogVisible.value = false
    getVideoList()
  } else {
    ElMessage.error(response.message || '上传失败')
  }
  uploading.value = false
}

// 上传失败处理
const onUploadError = () => {
  ElMessage.error('上传失败')
  uploading.value = false
}

// 提交视频表单 - 修复后的版本
const submitVideo = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要上传的视频文件')
    return
  }
  
  const file = fileList.value[0].raw
  
  // 增强文件验证
  if (!file || typeof file !== 'object' || !file.type.includes('video/')) {
    ElMessage.error('请上传有效的视频文件!')
    return
  }
  if (file.size / 1024 / 1024 >= 500) {
    ElMessage.error('视频大小不能超过 500MB!')
    return
  }
  
  // 创建FormData对象，确保正确添加文件
  const formData = new FormData()
  formData.append('file', file)  // 确保文件作为文件对象正确发送
  formData.append('courseId', props.course_id)
  formData.append('chapterId', props.chapter_id)
  formData.append('title', videoForm.value.title || file.name)
  formData.append('description', videoForm.value.description)
  formData.append('coverUrl', videoForm.value.coverUrl)
  formData.append('sort', videoForm.value.sort)
  formData.append('isFree', videoForm.value.isFree)
  formData.append('cost', videoForm.value.cost || 0)
  formData.append('userId', '1')
  
  try {
    uploading.value = true
    // 直接发送请求，确保multipart/form-data格式正确
    const response = await request.post('/video/upload/file', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.code === 100) {
      ElMessage.success('上传成功')
      uploadDialogVisible.value = false
      fileList.value = [] // 清空文件列表
      getVideoList()
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  } catch (error) {
    console.error('上传错误:', error)
    ElMessage.error('上传失败：' + (error.message || '网络错误'))
  } finally {
    uploading.value = false
  }
}

// 更新视频信息
const updateVideo = async () => {
  try {
    const response = await request.put('/video/update', editForm.value)
    if (response.code === 100) {
      ElMessage.success('更新成功')
      editDialogVisible.value = false
      getVideoList()
    } else {
      ElMessage.error(response.message || '更新失败')
    }
  } catch (error) {
    ElMessage.error('网络错误')
  }
}

// 删除视频
const deleteVideo = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该视频吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await request.delete(`/video/delete/${id}`)
    if (response.code === 100) {
      ElMessage.success('删除成功')
      getVideoList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      ElMessage.error('网络错误')
    }
  }
}

// 组件挂载时获取视频列表
onMounted(() => {
  console.log('VideoView组件挂载，章节ID:', props.chapter_id)
  if (props.chapter_id) {
    getVideoList()
  }
})

// 监听章节ID变化，当切换章节时自动更新视频列表
watch(() => props.chapter_id, (newChapterId) => {
  console.log('章节ID变化，重新获取视频列表，新章节ID:', newChapterId)
  if (newChapterId) {
    getVideoList()
  } else {
    // 如果章节ID为空，清空视频列表
    videos.value = []
  }
}, { immediate: true })
</script>

<style scoped lang="scss">
.video-view-wrapper {
  .video-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding: 8px 0;
    
    h4 {
      margin: 0;
      color: #333;
      font-size: 14px;
    }
  }
  
  .video-placeholder {
    padding: 30px 0;
    text-align: center;
  }
  
  .video-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .video-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    background-color: #fff;
    
    &:hover {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    }
  }
  
  .video-info {
    display: flex;
    gap: 12px;
    flex: 1;
  }
  
  .video-thumbnail {
    flex-shrink: 0;
    width: 120px;
    height: 80px;
    overflow: hidden;
    border-radius: 4px;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .no-cover {
      width: 100%;
      height: 100%;
      background-color: #f0f0f0;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
    }
  }
  
  .video-details {
    flex: 1;
    min-width: 0;
  }
  
  .video-title {
    margin: 0 0 8px 0;
    font-size: 14px;
    color: #333;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  
  .video-meta {
    display: flex;
    gap: 12px;
    margin-bottom: 4px;
    font-size: 12px;
    color: #666;
    
    .free-tag {
      background-color: #67c23a;
      color: white;
      padding: 2px 6px;
      border-radius: 10px;
      font-size: 12px;
    }
    
    .cost-tag {
      background-color: #f56c6c;
      color: white;
      padding: 2px 6px;
      border-radius: 10px;
      font-size: 12px;
    }
  }
  
  .video-description {
    margin: 0;
    font-size: 12px;
    color: #999;
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }
  
  .video-actions {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
  }
}
</style>